package com.qingmu.club.minaapi.controller.member;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingmu.club.minaapi.custom.logic.*;
import com.qingmu.club.minaapi.enums.MagicGroupStatusEnum;
import com.qingmu.club.minaapi.plus.entity.*;
import com.qingmu.club.minaapi.plus.service.*;
import com.qingmu.club.minaapi.utils.ResponseObject;
import com.qingmu.club.minaapi.wechat.QrCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 拼团活动(会员端)
 *
 * @Author: duke
 * @Date: 2019-08-06 15:51
 */
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.POST, RequestMethod.GET})
@Api(value = "拼团活动(会员端)", description = "#拼团活动(会员端)")
@RequestMapping(value = "/member/magicgroup")
public class MemberMagicGroupController {

    @Autowired
    UsersService usersService;
    @Autowired
    CourseService courseService;
    @Autowired
    MagicGroupService magicGroupService;
    @Autowired
    MagicGroupRuleService magicGroupRuleService;
    @Autowired
    MagicGroupRunService magicGroupRunService;
    @Autowired
    MagicGroupJoinlistService magicGroupJoinlistService;
    @Autowired
    ClubShopService clubShopService;
    @Autowired
    MagicGroupLogic magicGroupLogic;

    @Autowired
    PushMessageLogic pushMessageLogic;

    @Autowired
    PushMessageService pushMessageService;

    private final static Logger logger = LoggerFactory.getLogger(MemberMagicGroupController.class);

    private int max_show = 9;
    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Value("${web.upload-path}")
    private String uploadPath;
    @Value("${web.imageService}")
    private String wanPath;


    @RequestMapping(value = "/hotGroup", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "热门拼团")
    public ResponseEntity getHotMagicGroup(
            @ApiParam(required = true, value = "获取数量(最大9)") @RequestParam(required = true) Integer showMax,
            @ApiParam(required = true, value = "门店ID") @RequestParam(required = true) String shopId
    ) {

        if (showMax == null || showMax > max_show)
            showMax = max_show;

        QueryWrapper<MagicGroup> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(MagicGroup::getIsHot, 1)
                .eq(MagicGroup::getIsValid, 1)
                .eq(MagicGroup::getShopId, shopId);
        IPage<MagicGroup> iPage = magicGroupService.page(new Page<>(1, showMax), qw);
        List<MagicGroup> lists = iPage.getRecords();
        List<QueryMagicGroupHomeLogic> results = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            QueryMagicGroupHomeLogic item = new QueryMagicGroupHomeLogic();
            BeanUtils.copyProperties(lists.get(i), item);
            //拼团规则
            List<MagicGroupRule> magicGroupRules = this.magicGroupRuleService.list(new QueryWrapper<MagicGroupRule>()
                    .lambda()
                    .eq(MagicGroupRule::getGroupId, item.getId()));
            item.setMagicGroupRule(magicGroupRules);
            //已经参数人数总
            int count = this.magicGroupJoinlistService.count(new QueryWrapper<MagicGroupJoinlist>());
            item.setJoinQty(count);

            //课程资料
            Course course = this.courseService.getById(item.getCourseId());
            item.setCover(course.getCourseImage());
            results.add(item);
        }
        return ResponseObject.successWithIpageObject(iPage, results);
    }

    @RequestMapping(value = "/today", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "今日拼团")
    public ResponseEntity getTodayMagicGroup(
            @ApiParam(required = true, value = "获取数量(最大9)") @RequestParam(required = true) Integer showMax,
            @ApiParam(required = true, value = "门店ID") @RequestParam(required = true) String shopId
    ) {

        if (showMax == null || showMax > 9)
            showMax = 9;

        QueryWrapper<MagicGroup> qw = new QueryWrapper<>();
        qw.lambda()
                .eq(MagicGroup::getIsToday, 1)
                .eq(MagicGroup::getIsValid, 1)
                .eq(MagicGroup::getShopId, shopId);
        IPage<MagicGroup> iPage = magicGroupService.page(new Page<>(1, showMax), qw);
        List<MagicGroup> lists = iPage.getRecords();
        List<QueryMagicGroupHomeLogic> results = new ArrayList<>();
        for (int i = 0; i < lists.size(); i++) {
            QueryMagicGroupHomeLogic item = new QueryMagicGroupHomeLogic();
            BeanUtils.copyProperties(lists.get(i), item);
            //拼团规则
            List<MagicGroupRule> magicGroupRules = this.magicGroupRuleService.list(new QueryWrapper<MagicGroupRule>()
                    .lambda()
                    .eq(MagicGroupRule::getGroupId, item.getId()));
            item.setMagicGroupRule(magicGroupRules);
            //已经参数人数总
            int count = this.magicGroupJoinlistService.count(new QueryWrapper<MagicGroupJoinlist>());
            item.setJoinQty(count);

            //课程资料
            Course course = this.courseService.getById(item.getCourseId());
            item.setCover(course.getCourseImage());
            results.add(item);
        }
        return ResponseObject.successWithIpageObject(iPage, results);
    }

    @RequestMapping(value = "/myGroup", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "我的拼团")
    public ResponseEntity getMyMagicGroup(
            @ApiParam(required = false, value = "门店ID") @RequestParam(required = false) String shopId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String memberId,
            @ApiParam(required = false, value = "拼团状态") @RequestParam(required = false) MagicGroupStatusEnum status,
            @ApiParam(required = false, value = "当前页", example = "1") @RequestParam(required = false) Integer page,
            @ApiParam(required = false, value = "每页数量", example = "10") @RequestParam(required = false) Integer pageSize
    ) {

        if (StringUtils.isEmpty(memberId)) {
            return ResponseObject.error(401, "无此用户.");
        }


        QueryWrapper<MagicGroupJoinlist> qw = new QueryWrapper<>();
        qw.lambda().eq(MagicGroupJoinlist::getUserId, memberId);
        List<MagicGroupJoinlist> joinLists = this.magicGroupJoinlistService.list(qw);

        if (joinLists == null || joinLists.size() == 0) {
            return ResponseObject.successNonePage();
        }

        String[] ids = new String[joinLists.size()];
        for (int i = 0; i < joinLists.size(); i++) {
            ids[i] = joinLists.get(i).getRunId();
        }


        QueryWrapper<MagicGroupRun> qw_run = new QueryWrapper<>();
        qw_run.lambda().in(MagicGroupRun::getId, ids);
        if (status != null) {
            qw_run.lambda().in(MagicGroupRun::getStatus, status);
        }


        IPage<MagicGroupRun> iPage = this.magicGroupRunService.page(new Page<>(page, pageSize), qw_run);
        List<MagicGroupRun> lists = iPage.getRecords();
        List<QueryMyMagicGroupLogic> results = new ArrayList<>();


        for (int i = 0; i < lists.size(); i++) {
            QueryMyMagicGroupLogic item = new QueryMyMagicGroupLogic();
            BeanUtils.copyProperties(lists.get(i), item);
            //拼团资料
            MagicGroup magicGroup = this.magicGroupService.getById(item.getGroupId());
            if (magicGroup != null) {
                Course course = this.courseService.getById(magicGroup.getCourseId());
                magicGroup.setCover(course.getCourseImage());
            }
            item.setMagicGroup(magicGroup);
            //拼团规则
            List<MagicGroupRule> magicGroupRules = this.magicGroupRuleService.list(new QueryWrapper<MagicGroupRule>()
                    .lambda()
                    .eq(MagicGroupRule::getGroupId, item.getGroupId()));
            item.setMagicGroupRule(magicGroupRules);
            //参与人列表
            List<MagicGroupJoinlist> joinlists = this.magicGroupJoinlistService.list(new QueryWrapper<MagicGroupJoinlist>()
                    .lambda()
                    .eq(MagicGroupJoinlist::getRunId, item.getId()
                    ));

            item.setMagicGroupJoinlists(joinlists);
            results.add(item);
        }


        if (results == null || results.size() == 0) {
            ResponseObject.successWithIpage(iPage);
        }
        return ResponseObject.successWithIpageObject(iPage, results);
    }


    @RequestMapping(value = "/groupDetail", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "拼团详情")
    public ResponseEntity getMgDetail(
            @ApiParam(required = true, value = "拼团ID") @RequestParam(required = true) String groupId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String memberId

    ) {

        MagicGroup magicGroup = this.magicGroupService.getById(groupId);
        if (magicGroup == null) {
            return ResponseObject.error(601, "无此团");
        }

        if (magicGroup.getIsValid() == 0) {
            return ResponseObject.error(602, "此拼团已被下架");
        }

        //课程资料
        Course course = this.courseService.getById(magicGroup.getCourseId());
        magicGroup.setCover(course.getCourseImage());
        QueryMagicGroupDetailLogic result = new QueryMagicGroupDetailLogic();
        result.setMagicGroup(magicGroup);

        //门店资料
        ClubShop shop = this.clubShopService.getById(magicGroup.getShopId());
        result.setShopName(shop.getShopName());


        //课程规则
        List<MagicGroupRule> magicGroupRules = this.magicGroupRuleService.list(new QueryWrapper<MagicGroupRule>()
                .lambda()
                .eq(MagicGroupRule::getGroupId, groupId)
                .orderByAsc(MagicGroupRule::getQtyBegin)
        );
        result.setMagicGroupRuleList(magicGroupRules);


        //判断是否开了此团团长
        MagicGroupJoinlist isJoinedGroup = this.magicGroupJoinlistService.getOne(new QueryWrapper<MagicGroupJoinlist>()
                .lambda()
                .eq(MagicGroupJoinlist::getGroupId, groupId)
                .eq(MagicGroupJoinlist::getUserId, memberId)
                .eq(MagicGroupJoinlist::getIsLeader, 1)
                .last("limit 1")
        );

        //我是团长
        if (isJoinedGroup != null) {
            //运行数据
            MagicGroupRun magicGroupRun = this.magicGroupRunService.getById(isJoinedGroup.getRunId());
            //更新核销状态
            magicGroupRun.setIsClose(isJoinedGroup.getIsClose());
            if(isJoinedGroup.getIsClose()==0) {//没核销可以从新开团
                result.setMagicGroupRun(magicGroupRun);
                result.setRunId(isJoinedGroup.getRunId());
                result.setTeamLearder(true);
                //成员列表
                List<MagicGroupJoinlist> joinLists = this.magicGroupJoinlistService.list(new QueryWrapper<MagicGroupJoinlist>()
                        .lambda()
                        .eq(MagicGroupJoinlist::getRunId, isJoinedGroup.getRunId())
                        .orderByAsc(MagicGroupJoinlist::getCreateTime)
                        .last("limit 5")
                );
                for(MagicGroupJoinlist join:joinLists){
                    Users user = this.usersService.getById(join.getUserId());
                    if(user!=null) {
                        join.setUserName(user.getUserName());
                        join.setUserAvatar(user.getUserIcon());
                    }
                }
                result.setJoinlistList(joinLists);
                //参与数量
                result.setJoinQty(joinLists == null ? 0 : joinLists.size());
            }
        }

        //判断是否参团团员
        List<MagicGroupJoinlist> joinlists = this.magicGroupJoinlistService.list(new QueryWrapper<MagicGroupJoinlist>()
                .lambda()
                .eq(MagicGroupJoinlist::getGroupId, groupId)
                .eq(MagicGroupJoinlist::getUserId, memberId)
                .eq(MagicGroupJoinlist::getIsLeader, 0)
        );

        if (joinlists != null && joinlists.size() > 0) {
            result.setJoined(true);
        } else {
            result.setJoined(false);
        }

        return ResponseObject.success(result);
    }

    @RequestMapping(value = "/groupDetailForRunid", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "拼团详情根据runid查询")
    public ResponseEntity getMgDetailForRunid(
            @ApiParam(required = true, value = "拼团ID") @RequestParam(required = true) String runId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String memberId

    ) {

        MagicGroupRun runMagic = this.magicGroupRunService.getById(runId);
        if (runMagic == null) {
            return ResponseObject.error(601, "无此团");
        }


        MagicGroup magicGroup = this.magicGroupService.getById(runMagic.getGroupId());
        if (magicGroup == null) {
            return ResponseObject.error(601, "无此团");
        }
        if (magicGroup.getIsValid() == 0) {
            return ResponseObject.error(602, "此拼团已被下架");
        }

        QueryMagicGroupDetailLogic result = new QueryMagicGroupDetailLogic();

        //获取门店
        ClubShop clubShop = this.clubShopService.getById(magicGroup.getShopId());
        result.setShopName(clubShop.getShopName());

        //成员列表
        List<MagicGroupJoinlist> joinLists = this.magicGroupJoinlistService.list(new QueryWrapper<MagicGroupJoinlist>()
                .lambda()
                .eq(MagicGroupJoinlist::getRunId, runMagic.getId())
                .orderByAsc(MagicGroupJoinlist::getCreateTime)
                .last("limit 5")
        );
        for(MagicGroupJoinlist join:joinLists){
            Users user = this.usersService.getById(join.getUserId());
            if(user!=null) {
                join.setUserName(user.getUserName());
                join.setUserAvatar(user.getUserIcon());
            }
        }
        result.setJoinlistList(joinLists);

        //参与数量
        result.setJoinQty(runMagic.getJoinQty());
        result.setMagicGroupRun(runMagic);
        result.setRunId(runMagic.getId());

        //课程资料
        Course course = this.courseService.getById(magicGroup.getCourseId());
        magicGroup.setCover(course.getCourseImage());
        result.setMagicGroup(magicGroup);


        //课程规则
        List<MagicGroupRule> magicGroupRules = this.magicGroupRuleService.list(new QueryWrapper<MagicGroupRule>()
                .lambda()
                .eq(MagicGroupRule::getGroupId, magicGroup.getId())
                .orderByAsc(MagicGroupRule::getCreateTime)
        );
        result.setMagicGroupRuleList(magicGroupRules);


        //判断是否参团
        MagicGroupJoinlist isJoinedGroup = this.magicGroupJoinlistService.getOne(new QueryWrapper<MagicGroupJoinlist>()
                .lambda()
                .eq(MagicGroupJoinlist::getRunId, runMagic.getId())
                .eq(MagicGroupJoinlist::getUserId, memberId)
                .last("limit 1")
        );

        if (isJoinedGroup == null) {
            result.setJoined(false);
        } else {
            result.setJoined(true);
            //如果我是团员，更新此团核销状态
            result.getMagicGroupRun().setIsClose(isJoinedGroup.getIsClose());
            result.setTeamLearder(isJoinedGroup.getIsLeader() == 1 ? true : false);
        }
        return ResponseObject.success(result);
    }

    @RequestMapping(value = "/join", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "加入拼团")
    public ResponseEntity joinRuningTeam(
            @ApiParam(required = true, value = "运行拼团ID") @RequestParam(required = true) String runId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String memberId

    ) {

        Users user = this.usersService.getById(memberId);
        if (user == null) {
            return ResponseObject.error(401, "无此用户");
        }

        MagicGroupRun magicGroupRun = this.magicGroupRunService.getById(runId);
        if (magicGroupRun == null) {
            return ResponseObject.error(601, "无此拼团");
        }
        MagicGroup magicGroup = this.magicGroupService.getById(magicGroupRun.getGroupId());
        if (magicGroup == null) {
            return ResponseObject.error(601, "拼团已不存在");
        }

        //判断是否成员
        List<MagicGroupJoinlist> magicGroupJoinlist = this.magicGroupJoinlistService.list(new QueryWrapper<MagicGroupJoinlist>()
                .lambda()
                .eq(MagicGroupJoinlist::getRunId, magicGroupRun.getId())
                .eq(MagicGroupJoinlist::getUserId, memberId)
        );

        if (magicGroupJoinlist != null && magicGroupJoinlist.size() > 0) {
            return ResponseObject.error(601, "你已经参加了此拼团，请不要重复加入");
        }

        //判断时间是否合法
        if (magicGroup.getIsAlways() == 1) {
            Date nowDate = new Date();
            if (nowDate.compareTo(magicGroup.getBeginDate()) == -1) {
                return ResponseObject.error(601, "对不起，拼团还没开始");
            }

            if (nowDate.compareTo(magicGroup.getEndDate()) == 1) {
                return ResponseObject.error(601, "对不起，拼团已经过期");
            }
        }





        //加入成员
        MagicGroupJoinlist joinlist = new MagicGroupJoinlist();
        joinlist.setGroupId(magicGroupRun.getGroupId());
        joinlist.setIsLeader(0);
        joinlist.setRunId(magicGroupRun.getId());
        joinlist.setUserAvatar(user.getUserIcon());
        joinlist.setUserId(user.getId());
        joinlist.setUserName(user.getUserName());
        boolean states = this.magicGroupJoinlistService.save(joinlist);
        if (states) {
            //更新参加人数数量
            magicGroupRun.setJoinQty(magicGroupRun.getJoinQty() + 1);

            //检查规则
            try {
                List<MagicGroupRule> rules = this.magicGroupRuleService.list(new QueryWrapper<MagicGroupRule>()
                        .lambda()
                        .eq(MagicGroupRule::getGroupId, magicGroupRun.getGroupId())
                        .orderByAsc(MagicGroupRule::getQtyBegin)
                );

                //如果达标了，直接修改成成功状态
                if (rules != null && rules.size() > 0 && magicGroupRun.getJoinQty() >= rules.get(0).getQtyBegin()) {
                    magicGroupRun.setStatus(MagicGroupStatusEnum.success.name());
                }

                //推送拼团成功模板消息
                Course course  = courseService.getById(magicGroup.getCourseId());
                if(course==null) {
                    return ResponseObject.error(601, "课程不存在");
                }

                PushMessage pushMessage = this.pushMessageLogic.queryPushMessageList(memberId);
                if(pushMessage!=null) {
                    this.pushMessageLogic.sendGroupSuccessTemplate(pushMessage.getOpenId(), pushMessage.getFormId(), course.getCourseName(), magicGroupRun.getJoinQty(), magicGroup.getGroupName(), user.getUserMobile());
                    pushMessage.setIsUse(true);
                    this.pushMessageService.updateById(pushMessage);
                }

            }catch (Exception e){
                  logger.error(e.getMessage());
            }
            this.magicGroupRunService.updateById(magicGroupRun);
        }

        return ResponseObject.success();

    }

    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "创建拼团")
    public ResponseEntity createRuningTeam(
            @ApiParam(required = true, value = "拼团ID") @RequestParam(required = true) String groupId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String memberId

    ) {

        Users user = this.usersService.getById(memberId);
        if (user == null) {
            return ResponseObject.error(401, "无此用户");
        }

        MagicGroup magicGroup = this.magicGroupService.getById(groupId);
        if (magicGroup == null) {
            return ResponseObject.error(601, "无此拼团");
        }

        //判断时间是否合法
        if (magicGroup.getIsAlways() == 1) {
            Date nowDate = new Date();
            if (nowDate.compareTo(magicGroup.getBeginDate()) == -1) {
                return ResponseObject.error(601, "对不起，拼团还没开始");
            }

            if (nowDate.compareTo(magicGroup.getEndDate()) == 1) {
                return ResponseObject.error(601, "对不起，拼团已经过期");
            }
        }

        //检查是否已经开过此团
        List<MagicGroupJoinlist> magicGroupJoinlist = this.magicGroupJoinlistService.list(new QueryWrapper<MagicGroupJoinlist>()
                .lambda()
                .eq(MagicGroupJoinlist::getUserId, memberId)
                .eq(MagicGroupJoinlist::getGroupId, groupId)

        );

        if (magicGroupJoinlist != null && magicGroupJoinlist.size() > 0) {
            return ResponseObject.error(601, "对不起，你已经参与过此拼团");
        }

        MagicGroupRun magicGroupRun = new MagicGroupRun();
        magicGroupRun.setGroupId(magicGroup.getId());
        magicGroupRun.setJoinQty(0);
        magicGroupRun.setLeaderId(user.getId());
        magicGroupRun.setStatus(MagicGroupStatusEnum.running.name());
        magicGroupRun.setIsAlways(magicGroup.getIsAlways());
        magicGroupRun.setBeginDate(magicGroup.getBeginDate());
        magicGroupRun.setEndDate(magicGroup.getEndDate());
        boolean status = this.magicGroupRunService.save(magicGroupRun);

        if (status) {
            MagicGroupJoinlist joinlist = new MagicGroupJoinlist();
            joinlist.setGroupId(magicGroup.getId());
            joinlist.setIsLeader(1);
            joinlist.setRunId(magicGroupRun.getId());
            joinlist.setUserAvatar(user.getUserIcon());
            joinlist.setUserId(user.getId());
            joinlist.setUserName(user.getUserName());
            this.magicGroupJoinlistService.save(joinlist);
        }


        return ResponseObject.success();

    }

    @RequestMapping(value = "/over", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "主动结束拼团")
    public ResponseEntity overMagicGroup(
            @ApiParam(required = true, value = "运行拼团ID") @RequestParam(required = true) String runId,
            @ApiParam(required = true, value = "会员ID") @RequestParam(required = true) String memberId

    ) {
        MagicGroupRun magicGroupRun = this.magicGroupRunService.getById(runId);
        if (magicGroupRun == null) {
            return ResponseObject.error(601, "对不起，无此有效的拼团");
        }

        if (magicGroupRun.getStatus().equals(MagicGroupStatusEnum.success.name())
                || magicGroupRun.getStatus().equals(MagicGroupStatusEnum.failure.name())) {
            return ResponseObject.error(601, "对不起，此团已过了结算期");
        }


        Users users = this.usersService.getById(memberId);
        if (users == null) {
            return ResponseObject.error(401, "无此用户");
        }

        List<MagicGroupRule> rules = this.magicGroupRuleService.list(new QueryWrapper<MagicGroupRule>()
                .lambda()
                .eq(MagicGroupRule::getGroupId, magicGroupRun.getGroupId())
                .orderByAsc(MagicGroupRule::getQtyBegin)
        );
        //判断是否达成最低条件
        if (rules == null || rules.size() == 0) {
            return ResponseObject.error(601, "结束失败,拼团规则数据异常");
        }

        //对比第一个规则
        if (magicGroupRun.getJoinQty() < rules.get(0).getQtyBegin()) {
            return ResponseObject.error(601, "结束失败,参与人数达不到指定标准");
        }


        magicGroupRun.setStatus(MagicGroupStatusEnum.success.name());
        boolean state = this.magicGroupRunService.updateById(magicGroupRun);

        //推送拼团成功模板消息
        MagicGroup magicGroup = this.magicGroupService.getById(magicGroupRun.getGroupId());
        if (magicGroup == null) {
            return ResponseObject.error(601, "拼团已不存在");
        }
        Course course  = courseService.getById(magicGroup.getCourseId());
        if(course==null) {
            return ResponseObject.error(601, "课程不存在");
        }

        PushMessage pushMessage = this.pushMessageLogic.queryPushMessageList(memberId);
        if(pushMessage!=null) {
            this.pushMessageLogic.sendGroupSuccessTemplate(pushMessage.getOpenId(), pushMessage.getFormId(), course.getCourseName(), magicGroupRun.getJoinQty(), magicGroup.getGroupName(), users.getUserMobile());
            pushMessage.setIsUse(true);
            this.pushMessageService.updateById(pushMessage);
        }

        return state ? ResponseObject.success() : ResponseObject.error();
    }


    @RequestMapping(value = "/groupSuccess", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ApiOperation(value = "拼团成功生成二维码")
    public ResponseEntity exchangeNow(
            @ApiParam(required = true, value = "会员id") @RequestParam(required = true) String userId,
            @ApiParam(required = true, value = "魔力拼团运行数据id") @RequestParam(required = true) String runId,
            @ApiParam(required = true, value = "课程id") @RequestParam(required = true) String courseId


    ) {
        Users users = this.usersService.getById(userId);
        if (users == null) {
            return ResponseObject.error(401, "作者信息找不到");
        }
        MagicGroupRun magicGroupRun = this.magicGroupRunService.getById(runId);
        if (magicGroupRun == null) {
            return ResponseObject.error(556, "拼团信息找不到");
        }

        QueryWrapper<MagicGroupJoinlist> qw = new QueryWrapper<>();
        qw.eq(MagicGroupJoinlist.RUN_ID, runId).eq(MagicGroupJoinlist.USER_ID, userId);
        List<MagicGroupJoinlist> magicGroupJoinlistList = magicGroupJoinlistService.list(qw);
        int createCodeType = 0;
        if (CollectionUtils.isEmpty(magicGroupJoinlistList)) {
            createCodeType = 1;
        }

        Course course = this.courseService.getById(courseId);
        if (course == null) {
            return ResponseObject.error(601, "课程不存在");
        }

//        if (clubUsers.getUserJf() < integralGoods.getGoodsPrice()){
//            return ResponseObject.error(555,"积分数量不够，请兑换其它商品");
//        }
        int type = 1;
        String courseCode = QrCodeUtil.createQrcode(uploadPath, "userId=" + userId + ",type=" + type + ",runId=" + runId + ",courseId=" + courseId + ",codeId=" + UUID.randomUUID().toString().replace("-", ""));//生成积分商品二维码
        if (org.springframework.util.StringUtils.isEmpty(courseCode)) {
            return ResponseObject.error(556, "二维码生成失败");
        }

        HashMap<String, Object> map = new HashMap<>();
        map.put("goodsCodeUrl", wanPath + courseCode);
        map.put("createCodeType", createCodeType);

        return ResponseObject.success(map);

    }





}
